// pages/mine/payment/payment.js
const app = getApp()
import util from "../../../utils/util.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showTime:false,
    monthActive: new Date().getTime(),//页面显示的值
    currentDate: new Date().getTime(),//当前选择值
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    lastDate: new Date().getTime(),//记录确认时间的值
    roomVisible: false,
    rooms:[],
    roomActive:"",
    roomCurrentIndex:0,
    roomLoading:false,
    formData:[],//查出来的数据
    fix:false,
    loading:false,

    roomVisable:true,
    showQuickBtn:true,//是否显示快捷支付按钮

    parameter:"",//子页面传回的参数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.getMonthData()
  },
  /**
   * 生命周期函数
   */
  onShow: function(){
    if(this.data.parameter == "paySuccess"){
      this.getCurrentData()
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getCurrentData()
  },
  /**
   * 上拉加载更多
   */
  onReachBottom(e) {
    this.getCurrentData(false)
  },
  
  /**
   * 滑动事件
   */
  onPageScroll:function(e){
    if(e.scrollTop >= 247){
      this.setData({ fix:true })
    }else{
      this.setData({ fix:false })
    }
  },
  // 跳转
  goToPage(e) {
    wx.navigateTo({
      url: "eletric/eletric?type=" + e.currentTarget.dataset.type + "&status="+e.currentTarget.dataset.status,
    })
  },
  //列表跳详情页
  goToDetail(e){
    let option = e.currentTarget.dataset
    wx.navigateTo({
      url: 'eletric/eletricDetail/eletricDetail?type=' + option.type + '&status=' + option.status +'&id='+ option.id,
    })
  },
  onClose() {
    this.setData({ showTime: false });
  },
  //获取时间数据
  getMonthData(){
    app.globalData.request("post","/applet/wx_pay/getMonth",{
      token:wx.getStorageSync("token"),
      id:wx.getStorageSync("id")
    })
    .then(res => {
      this.setData({
        maxDate: new Date().getTime(),
        minDate: res.data*1000,
        currentDate: new Date().getTime(),
        monthActive: util.formatTime(new Date().getTime(),'Y-M'),
        lastDate: new Date().getTime(),
      })
      this.getRooms()
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon:"none"
      })
    })
  },
  //展示时间选择器
  showTimePicker(){
    this.setData({showTime:true})
  },
  //时间选择--确认
  confirmTime(event) {
    console.log(event.detail)
    this.setData({ 
      showTime: false, 
      currentDate: event.detail,
      monthActive: util.formatTime(event.detail,'Y-M'),
      lastDate: event.detail
    });
    console.log(this.data.lastDate)
    this.getCurrentData()
  },
  // 时间选择--取消
  cancelTime(){
    this.setData({ showTime: false, currentDate: this.data.lastDate})
  },
  // 时间选择--记录上一次确认选中的值
  onInput(event){
    this.setData({currentDate:event.detail})
  },
  onChange(event){
    console.log(event.detail.getValues())
    let year = new Date(this.data.currentDate).getFullYear()
    let month = new Date(this.data.currentDate).getMonth()
    month = month <= 9 ? "0" + month + 1 : month + 1
    event.detail.setValues([year, month])
  },
  // 获取所有房间号
  getRooms(){
    app.globalData.request("post","/applet/wx_pay/billRoomNumber",{
      token:wx.getStorageSync("token"),
      id:wx.getStorageSync("id")
    })
    .then(res => {
      this.setData({
        rooms:res.data,
        roomActive:res.data[0]
      })
      if(res.data.length == 0){
        this.setData({
          roomVisable: false
        })
      }else{
        this.setData({roomVisable:true})
      }
      this.getCurrentData()
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon:"none"
      })
    })
  },
  //房间选择--显示
  showRooms(){
    this.setData({ roomVisible: true })
  },
  // 房间选择--取消
  onRoomCancel(){
    this.setData({
      roomVisible:false
    })
    this.selectComponent("#roomPicker").setIndexes([this.data.roomCurrentIndex])
  },
  //房间选择--确定
  onRoomConfirm(event){
    console.log(event)
    this.setData({
      roomVisible:false,
      roomCurrentIndex:event.detail.index,
      roomActive:event.detail.value
    })
    this.selectComponent("#roomPicker").setIndexes([this.data.roomCurrentIndex])
    this.getCurrentData()
  },
  // 根据时间和房号查出数据
  getCurrentData(){
    wx.showLoading({ title: '加载中' })
    this.setData({
      loading: true
    })
    app.globalData.request("post", "/applet/wx_pay/billTimeList", {
      token: wx.getStorageSync("token"),
      room_number: this.data.roomActive,
      time: util.formatTime(this.data.currentDate,'Y-M'),
      id:wx.getStorageSync('id')
    })
    .then(res => {
      console.log(JSON.stringify(res.data))
      // 判断数据为空&没有未缴把按钮隐藏
      if (res.data) {
        if (res.data.length > 0) {
          res.data.map(item => {
            if (item.status == 1) {
              this.setData({
                showQuickBtn: true
              })
            } else {
              this.setData({
                showQuickBtn: false
              })
            }
          })
        } else {
          this.setData({
            showQuickBtn: false
          })
        }
      }
      this.setData({
        loading: false,
        formData: res.data,
      })
      wx.nextTick(() => {
        wx.hideLoading()
        wx.stopPullDownRefresh();
      })
    }).catch(err => {
      this.setData({
        loading: false
      })
      wx.hideLoading()
      // wx.showToast({
      //   title: err.msg,
      //   icon: "none"
      // })
    })
  },
  // 一键支付
  quickPay(){
    let self = this
    if (self.data.formData.length <= 0){
      wx.showToast({
        title: '暂无未缴账单',
        icon: "none"
      })
    }else{
      let id_one = [], id_two = [], id_three = [], id_four = [], id_five = []
      let dataObj = {}
      self.data.formData.forEach(item => {
        if (item.status == 1 || item.status == 4) {
          switch (item.bill_type) {
            case 1:
              id_one.push(item.id);
              break;
            case 2:
              id_two.push(item.id)
              break;
            case 3:
              id_three.push(item.id)
              break;
            case 4:
              id_four.push(item.id)
              break;
            case 5:
              id_five.push(item.id)
              break;
          }
        }
        dataObj = { id_one, id_two, id_three, id_four, id_five }
      })
      console.log(dataObj)
      wx.showLoading({
        title: '支付中',
      })
      app.globalData.request("post", "/applet/wx_pay/onePay", {
        id: wx.getStorageSync("id"),
        bill_ids: dataObj
      })
        .then(res => {
          // console.log(res)
          wx.hideLoading()
          wx.requestPayment({
            timeStamp: res.msg.timeStamp,
            nonceStr: res.msg.nonceStr,
            package: res.msg.package,
            signType: res.msg.signType,
            paySign: res.msg.paySign,
            success(res) {
              wx.showModal({
                title: '支付成功!',
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    // console.log("1"+res.confirm)
                    self.getCurrentData()
                  }
                },
                fail(err){
                  // console.log("2"+JSON.stringify(err))
                },
                complete(obj){
                  // console.log("3"+JSON.stringify(obj))
                }
              })
            },
            fail(err) {
              wx.showModal({
                title: '支付失败!',
                content: err
              })
            }
          })
        }).catch(err => {
          console.log(err)
          wx.hideLoading()
          // wx.showToast({
          //   title: err.msg,
          //   icon: "none"
          // })
        })
    }
    
  }
})